﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

public partial class RequestCredit : System.Web.UI.Page
{
    BankDataDataContext db = new BankDataDataContext();

    protected void Page_Load(object sender, EventArgs e)
    {       
        if (Roles.IsUserInRole("Operator"))
        {
            UserCommentAboutDate.Visible = false;
            UserCommentAboutDateLabel.Visible = false;
        }
        string creditId = null;
        if (Session["creditId"] != null)
        {
            creditId = Session["creditId"].ToString();
            //setValidators(creditId);
        }
        string clientId = "";
        try
        {
            clientId = Session["clientId"].ToString();
        }
        catch { }
        SqlDataSourceForm.SelectParameters["CreditId"].DefaultValue = CreditList.SelectedValue;
        OrganizationForm.DataBind();
        if (clientId != "")
        {
            var profiles = from profile in db.UserProfiles where profile.ProfileId == Convert.ToInt32(clientId) select profile;
            UserProfile clientProfile = profiles.First();
            CompanyName.Text = clientProfile.Company.CompanyName;
            CompanyName.Enabled = false;
            OrganizationForm.Enabled = false;
            HeadName.Text = clientProfile.CompanyHead;
            HeadName.Enabled = false;
            CompanyAddress.Text = clientProfile.Address;
            CompanyAddress.Enabled = false;
            CompanyPhone.Text = clientProfile.CompanyPhone;
            CompanyPhone.Enabled = false;
            CompanyEmail.Text = clientProfile.aspnet_User.aspnet_Membership.Email;
            CompanyEmail.Enabled = false;
            CompanyProfit.Text = clientProfile.LastTwoYearsProfit.ToString();
            CompanyProfit.Enabled = false;
            HeadAddress.Text = clientProfile.CompanyHeadAddress;
            HeadAddress.Enabled = false;
            HeadPhone.Text = clientProfile.CompanyHeadPhone;
            HeadPhone.Enabled = false;
            HaveCredit.Checked = clientProfile.HasCredit;
            HaveCredit.Enabled = false;
        }
    }

    protected void setValidators(string creditId)
    {
        var credits = from credit in db.Credits where credit.CreditID == Convert.ToInt32(creditId) select credit;
        Credit selectedCredit = credits.First();
        var curs = from cur in db.Currencies where cur.CurrencyID == Convert.ToInt32(CurrencyList.SelectedValue) select cur;
        RangeValidatorTermLength.MaximumValue = selectedCredit.MaximumTerm.ToString();
        RangeValidatorTermLength.MinimumValue = selectedCredit.MinimumTerm.ToString();
        RangeValidatorTermLength.Text = string.Format("Срок должен быть от {0} до {1} ", selectedCredit.MinimumTerm, selectedCredit.MaximumTerm);
        RangeValidatorAmount.MaximumValue = ((int)(selectedCredit.MaxValue * curs.First().USDExchangeRate)).ToString();
        RangeValidatorAmount.MinimumValue = ((int)(selectedCredit.MinValue * curs.First().USDExchangeRate)).ToString();
        RangeValidatorAmount.Text = string.Format("Сумма кредита должна быть от {0} до {1}", ((int)(selectedCredit.MinValue * curs.First().USDExchangeRate)), ((int)(selectedCredit.MaxValue * curs.First().USDExchangeRate)));
    }

    protected void RequestCreditButton_Click(object sender, EventArgs e)
    {
        string clientId = "";
        try
        {
            clientId = Session["clientId"].ToString();
        }
        catch { }
        if (clientId != "")
        {
            addRequest(Convert.ToInt32(clientId));
        }
        else
        {
            int profileId = addProfile();
            if (profileId != -1)
            {
                addRequest(profileId);
            }
        }
        if (Roles.IsUserInRole("Operator"))
        {
            Response.Redirect("~/Operator/Clients.aspx");
        }
        else
        {
            Response.Redirect("~/Credit.aspx?id=" + CreditList.SelectedValue);
        }
    }

    [System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
    public static string[] GetCompletionList(string prefixText, int count, string contextKey)
    {
        BankDataDataContext db = new BankDataDataContext();
        var companiesName = from companies in db.Companies where companies.CompanyName.StartsWith(prefixText) select companies.CompanyName;
        return companiesName.ToArray();
    }

    protected int addProfile()
    {
        var company = from companies in db.Companies where companies.CompanyName == CompanyName.Text select companies;
        if (company.Count() == 0)
        {
            ErrorLabel.Text = "Неверное название предприятия";
            return -1;
        }
        var companyIdInUserProfiles = from profiles in db.UserProfiles where profiles.CompanyId == Convert.ToInt32(company.First().CompanyId) select profiles.CompanyId;
        if (companyIdInUserProfiles.Count() > 0)
        {
            ErrorLabel.Text = "Уже существует аккаунт для данного предприятия";
            return -1;
        }
        UserProfile userProfile = new UserProfile();
        userProfile.CompanyId = Convert.ToInt32(company.First().CompanyId);
        userProfile.CompanyHead = HeadName.Text;
        userProfile.Address = CompanyAddress.Text;
        userProfile.CompanyPhone = CompanyPhone.Text;
        userProfile.CompanyHeadPhone = HeadPhone.Text;
        userProfile.CompanyHeadAddress = HeadAddress.Text;
        userProfile.CompanyEmail = CompanyEmail.Text;
        userProfile.LastTwoYearsProfit = Convert.ToInt32(CompanyProfit.Text);
        userProfile.HasCredit = HaveCredit.Checked;
        db.UserProfiles.InsertOnSubmit(userProfile);
        db.SubmitChanges();
        return userProfile.ProfileId;
    }

    protected void addRequest(int clientId)
    {
        CreditRequest newCreditRequest = new CreditRequest();
        newCreditRequest.CreditId = Convert.ToInt32(CreditList.SelectedValue);
        newCreditRequest.Amount = Convert.ToInt32(Amount.Text);
        newCreditRequest.TermLength = Convert.ToInt32(TermLength.Text);
        newCreditRequest.UserProfileId = clientId;
        newCreditRequest.CurrencyId = Convert.ToInt32(CurrencyList.SelectedValue);
        newCreditRequest.RequestStatusId = 0;
        newCreditRequest.CreditFacilitiesFormId = Convert.ToInt32(CreditFacilitiesFormList.SelectedValue);
        if (UserCommentAboutDate.Visible)
        {
            newCreditRequest.UserComment = UserCommentAboutDate.Text;
        }
        db.CreditRequests.InsertOnSubmit(newCreditRequest);
        db.SubmitChanges();
    }

    protected void CreditList_DataBound(object sender, EventArgs e)
    {
        string creditId = null;
        if (Session["creditId"] != null)
        {
            creditId = Session["creditId"].ToString();
        }
        if (creditId != null)
        {
            CreditList.Items.FindByValue(creditId).Selected = true;
        }
        else
        {
            CurrencyList.DataBind();
            setValidators(CreditList.SelectedValue);
        }
        SqlDataSourceForm.SelectParameters["CreditId"].DefaultValue = CreditList.SelectedValue;
        OrganizationForm.DataBind();
        CurrencyList.DataBind();
        setValidators(CreditList.SelectedValue);
    }

    protected void OrganizationForm_DataBound(object sender, EventArgs e)
    {
        string clientId = "";
        try
        {
            clientId = Session["clientId"].ToString();
        }
        catch { }
        if (clientId != "")
        {
            var profiles = from profile in db.UserProfiles where profile.ProfileId == Convert.ToInt32(clientId) select profile;
            UserProfile clientProfile = profiles.First();
            OrganizationForm.Items.FindByValue(clientProfile.Company.OrganitionalFormId.ToString()).Selected = true;
        }
    }

    protected void CreditList_SelectedIndexChanged(object sender, EventArgs e)
    {
        ViewState["CurList"] = null;
        CurrencyList.DataBind();
        SqlDataSourceForm.SelectParameters["CreditId"].DefaultValue = CreditList.SelectedValue;
        CreditFacilitiesFormList.DataBind();
        setValidators(CreditList.SelectedValue);
    }
    protected void CompanyName_TextChanged(object sender, EventArgs e)
    {
        var companies = from company in db.Companies where company.CompanyName == CompanyName.Text select company;
        if (companies.Count() > 0)
        {
            Company editCompany = companies.First();
            OrganizationForm.SelectedValue = editCompany.OrganitionalFormId.ToString();
        }
    }
    protected void CurrencyList_SelectedIndexChanged(object sender, EventArgs e)
    {
        setValidators(CreditList.SelectedValue);
        ViewState["CurList"] = CurrencyList.SelectedValue;
    }
    protected void CurrencyList_DataBound(object sender, EventArgs e)
    {
        if (ViewState["CurList"] != null)
        {
            CurrencyList.SelectedValue = ViewState["CurList"].ToString();
        }
    }
}